package src.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Connexion au serveur lors de la connexion d'un utilisateur
 * @author caro
 *
 */
public class CommunicationClient extends Thread{
	/*
	 * connection indique si le client est authentifié sur le serveur
	 */
		public boolean connection=false;
		String email;
		String mDp;
		int action;
		Socket comm = null;
	    InputStream is = null;
		private BufferedReader _in; // pour gestion du flux d'entrée

	    /**
	     * 
	     * @return true: connection au serveur réussie 
	     * 		   false: connection non établie
	     */
	    public CommunicationClient(String mail,String mDep,int act)
	    {
	    	email=mail;
	    	mDp=mDep;
	    	action=act;
	    }
	    public void run()
	    {
	    	try
	    	{
	    		comm = new Socket("localhost",18888); 
	    		if(action==1)
	    		{
	    			String mess="C"+email+";"+mDp+"\n";
	    			System.out.println(mess);
	    			comm.getOutputStream().write(mess.getBytes());
	    		}
	    		
	    		is = comm.getInputStream();	    		
		    	_in = new BufferedReader(new InputStreamReader(is));

		    	char charCur[] = new char[1]; 
		    	if(_in.read(charCur, 0, 1) != -1)
		    	{
		    		if(charCur[0]=='C')
		    		{
		    			if(_in.read(charCur, 0, 1) != -1)
		    			{
		    				if(charCur[0]=='1')
		    					connection=true;
		    				else
		    					connection=false;
		    			}
		    		}
		    	}	    		
		    	  while(_in.read(charCur, 0, 1) != -1) 
		    	  {
		    		  System.out.println(charCur[0]);
		    	  }


	    	}
	    	
	    	catch(Exception e)
	    	{
	    		System.err.println("Exception " + e.toString());
	    	}
	    	finally
	    	{
	    		if (is!=null)
	    			try {
	    				is.close();
	    			} catch (IOException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
	    			if (comm!=null)
	    				try {
	    					comm.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
			}
	    }
	    
}

}
